﻿using AutoMapper;
using MediatR;
using SCM.Domain;
using Warehouse.Api.Write.AllGCotion.Command;
using Warehouse.Domian.Model;
using Warehouse.ErrorCode;
using Warehouse.Infrastructrue.Implenment;

namespace Warehouse.Api.Write.AllGCotion.Hanlder
{
    public class AddInventoryCommandHanlder : IRequestHandler<AddInventoryCommand, ApiResult<int>>
    {
        IMapper mapper;
        DbContext db;
        ILogger<AddInventoryCommandHanlder> _logger;

        public AddInventoryCommandHanlder(IMapper mapper, DbContext db, ILogger<AddInventoryCommandHanlder> logger)
        {
            this.mapper = mapper;
            this.db = db;
            this._logger = logger;
        }
        /// <summary>
        /// 添加库存
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>

        public async Task<ApiResult<int>> Handle( AddInventoryCommand request,
           CancellationToken cancellationToken)
        {
             ApiResult<int> result = new ApiResult<int>();

            try
            {
                
                var carrier = mapper.Map<InventoryModel>(request);
                int r = await db.SqlSugar.Insertable(carrier).ExecuteCommandAsync();
                if (r > 0)
                {
                    result.Msg = "库存盘点添加成功";
                    result.Data = r;
                    result.Code = ApiEume.Success;
                    _logger.LogInformation(result.Msg);
                }
                else
                {
                    result.Msg = "库存盘点添加失败";
                    result.Data = r;
                    result.Code = ApiEume.Error;
                    _logger.LogError(result.Msg);
                }
                return await Task.FromResult(result);
            }
            catch (Exception ex)
            {
               
            }

            return result;
        }
    }
}


